package com.leyou.user.controller;

import com.leyou.common.exception.pojo.LyException;
import com.leyou.user.service.UserService;
import entity.AddressDTO;
import entity.User;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.stream.Collectors;

@RestController
public class UserController {
    @Autowired
    private UserService userService;
    /**
     * GET /check/{data}/{type}
     */
    @GetMapping("/check/{data}/{type}")
    @ApiOperation(value = "校验用户名数据是否可用，如果不存在则可用")
    @ApiResponses({
            @ApiResponse(code = 200,message = "校验结果有效true或false代表不存在则可用"),
            @ApiResponse(code=400,message = "请求参数有误,比如type不指定值")
    })
    public ResponseEntity<Boolean> checkData(
            @ApiParam(value = "要校验的数据")
            @PathVariable("data") String data,
            @ApiParam(value = "数据类型 1:用户名 2：手机号",example = "1")
            @PathVariable("type") Integer type){
        Boolean isCanUse = userService.checkData(data, type);
        return ResponseEntity.ok(isCanUse);
    }
    /**
     * 发送短信验证码
     */
     @PostMapping("/code")
    public ResponseEntity<Void> sendVerifyCode(@RequestParam("phone") String phone){
         System.out.println("phone = " + phone);
         userService.sendVerifyCode(phone);
         return ResponseEntity.status(HttpStatus.CREATED).build();

     }
    /**
     * 注册业务
     */
    @PostMapping("/register")
    public ResponseEntity<Void> register(@Valid User user,BindingResult result, @RequestParam("code") String code){
        //自定义报错信息
        if(result.hasErrors()){
            //取出错误提示
            String errorMsg = result.getFieldErrors().stream().map(FieldError::getDefaultMessage).collect(Collectors.joining("|"));
            throw new LyException(500,errorMsg);
        }
        userService.register(user,code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }
    /**
     * 校验用户名和密码是否正确
     */
    @GetMapping("/query")
    public ResponseEntity<User> query(
            @RequestParam("username") String username,
            @RequestParam("password")  String password
    ){
        User user = userService.query(username, password);
          return ResponseEntity.ok(user);
    }
    /**
     * 根据地址ID查询用户的收货地址
     */
    @GetMapping("/address")
    public ResponseEntity<AddressDTO> findAddressId(
            @RequestParam("userId") Long userId,
            @RequestParam("id") Long id
    ){
        AddressDTO address = userService.findAddressId(userId, id);
        return ResponseEntity.ok(address);

    }
}
